(function () {

    window.$render = {
        rooms: renderRooms,
        chatItem: renderChatlItem,
        optsGroup: renderBottomOptsGroup,
        chesses: renderChesses,
        infoBoxUser: renderInfoBoxUser,
        infoBoxChess: renderInfoBoxChess,
        infoBoxTips: renderInfoBoxTips,
    };

    let chessArr = [{
            id: "a1",
            x: 2,
            y: 2
        },
        {
            id: "a2",
            x: 152,
            y: 2
        },
        {
            id: "a3",
            x: 298,
            y: 2
        },
        {
            id: "a4",
            x: 298,
            y: 148
        },
        {
            id: "a5",
            x: 298,
            y: 298
        },
        {
            id: "a6",
            x: 152,
            y: 298
        },
        {
            id: "a7",
            x: 2,
            y: 298
        },
        {
            id: "a8",
            x: 2,
            y: 148
        },
        {
            id: "b1",
            x: 52,
            y: 52
        },
        {
            id: "b2",
            x: 152,
            y: 52
        },
        {
            id: "b3",
            x: 250,
            y: 52
        },
        {
            id: "b4",
            x: 250,
            y: 148
        },
        {
            id: "b5",
            x: 250,
            y: 250
        },
        {
            id: "b6",
            x: 152,
            y: 250
        },
        {
            id: "b7",
            x: 52,
            y: 250
        },
        {
            id: "b8",
            x: 52,
            y: 148
        },
        {
            id: "c1",
            x: 102,
            y: 100
        },
        {
            id: "c2",
            x: 152,
            y: 100
        },
        {
            id: "c3",
            x: 200,
            y: 100
        },
        {
            id: "c4",
            x: 200,
            y: 148
        },
        {
            id: "c5",
            x: 200,
            y: 198
        },
        {
            id: "c6",
            x: 152,
            y: 198
        },
        {
            id: "c7",
            x: 102,
            y: 198
        },
        {
            id: "c8",
            x: 102,
            y: 148
        }
    ];

    // 渲染列表  => 绑定点击事件: 1. 创建房间 2. 进入房间
    function renderRooms(ele, rooms, enterFn) {
        ele.innerHTML = '';
        if (!rooms || JSON.stringify(rooms) == '{}' || rooms.length == 0) {
            let oDiv = document.createElement('div');
            oDiv.innerText = '+';
            oDiv.classList.add('room');
            oDiv.classList.add('room-create');
            ele.prepend(oDiv);
            oDiv.addEventListener('click', enterFn);
        } else {
            rooms.forEach(item => {
                let oDiv = document.createElement('div');
                oDiv.innerHTML = `
                    <span>${item.title}</span>
                    <span>${'房号:'+item.id}</span>
                    <span>${item.user + '(' + item.total + '人)'}</span>
                    <span>${item.password?'密码':'公开'}</span>
                    <div class="btn">
                        <span>${item.start?'观战':'加入'}</span>
                    </div>
                    `;
                oDiv.classList.add('room');
                if (item.start) {
                    oDiv.classList.add('start');
                    ele.append(oDiv);
                } else {
                    ele.prepend(oDiv);
                }
                let enterBtn = oDiv.getElementsByClassName('btn')[0];
                enterBtn.addEventListener('click', () => {
                    enterFn(item.id);
                })
            });
        }
    }

    /**
     * 渲染棋子 ， 绑定点击事件fn(); 一切操作棋子的入口函数
     * @param {Object} ele SVG棋子容器g元素
     * @param {Object} room {black:'',white:''}
     * @param {Object} fn 绑定的点击事件
     */
    function renderChesses(ele, room, fn) {
        ele.innerHTML = '';
        // 通过改变容器g内的use标签href，改变棋子状态
        chessArr.forEach(item => {
            let oUse = document.createElementNS('http://www.w3.org/2000/svg', 'use');
            // 棋子样式
            if (room.black.length > 0 && room.black.indexOf(item.id) > -1) {
                oUse.setAttribute("href", "#chess-black")
            } else if (room.white.length > 0 && room.white.indexOf(item.id) > -1) {
                oUse.setAttribute("href", "#chess-white")
            } else if (room.ate.length > 0 && room.ate.indexOf(item.id) > -1) {
                oUse.setAttribute("href", "#chess-red")
            } else {
                oUse.setAttribute("href", "#chess-transparent")
            }
            // 棋子的SVG坐标
            oUse.setAttribute("x", item.x);
            oUse.setAttribute("y", item.y);
            // 编号，发送给服务器，代表游戏棋子，游戏规则判断的依据
            oUse.setAttribute("data-id", item.id);

            ele.appendChild(oUse);
        })
        ele.addEventListener("click", fn);
    }

    function renderInfoBoxUser(ele, room) {
        let masterColor = 'black';
        let oppColor = 'white';
        // 确定前置图标的颜色
        if (!room.user[1]) {
            oppColor = 'empty'
        } else {
            if (room.offensive == 1) {
                masterColor = 'white'
                oppColor = 'black'
            }
        }
        // 删除首尾节点
        if (ele.children.length > 2) {
            ele.removeChild(ele.children[2]);
            ele.removeChild(ele.children[0]);
        }

        // 新增首尾节点
        let oDivMaster = document.createElement('div')
        oDivMaster.innerText = `${room.user[0].name || ''}`;
        oDivMaster.classList.add(`${'icon-chess-'+masterColor}`)
        ele.prepend(oDivMaster);

        let oDivOpp = document.createElement('div')
        oDivOpp.innerText = `${room.user[1]?room.user[1].name:''}`;
        oDivOpp.classList.add(`${'icon-chess-'+oppColor}`)
        ele.append(oDivOpp);
    }

    function renderInfoBoxChess(ele, room) {
        console.log("tip xianshi ??????");
        
        let masterColor = 'black';
        let oppColor = 'white';
        // 确定前置图标的颜色
        if (!room.user[1]) {
            oppColor = 'empty'
        } else {
            if (room.offensive == 1) {
                masterColor = 'white'
                oppColor = 'black'
            }
        }

        // 是否准备，轮到谁下棋，是否成三，是否吃棋，棋子数目

        // 手里的棋子
        let masterHandChessNum, oppHandChessNum;
        if (room.start) {
            if (room.count < 10) {
                if (room.offensive == room.turn) {
                    masterHandChessNum = `${10 - room.count}`;
                    oppHandChessNum = `${10 - room.count}`;

                } else {
                    if (room.offensive == 0) {
                        masterHandChessNum = `${10 - (room.count+1)}`;
                        oppHandChessNum = `${10 - room.count}`;
                        if (room.eat) {

                        }
                    } else {
                        masterHandChessNum = `${10 - room.count}`;
                        oppHandChessNum = `${10 - (room.count+1)}`;
                    }
                }

                if (room.eat) {
                    if (room.turn == 0) {
                        masterHandChessNum -= 1;
                    } else {
                        oppHandChessNum -= 1;
                    }
                }

            } else {
                masterHandChessNum = '0';
                oppHandChessNum = '0';
            }
        } else {
            masterHandChessNum = '0';
            oppHandChessNum = '0';
        }

        // 删除首尾节点
        if (ele.children.length > 2) {
            ele.removeChild(ele.children[2]);
            ele.removeChild(ele.children[0]);
        }

        // 新增首尾节点
        let oDivMaster = document.createElement('div')
        if (room.start) {
            // 下棋
            if (room.count <= 9) {
                oDivMaster.innerHTML = `
                <span>手棋:</span>
                <span ${"class='icon-chess-"+masterColor+"'"}>${masterHandChessNum}</span>
               `;
            } else {
                oDivMaster.innerHTML = `
                <span>棋盘:</span>
                <span ${"class='icon-chess-"+masterColor+"'"}>${room[masterColor].length}</span>
                `;
            }
        }
        ele.prepend(oDivMaster);

        let oDivOpp = document.createElement('div')
        if (room.start) {
            // 下棋
            if (room.count <= 9) {
                oDivOpp.innerHTML = `
                <span>手棋:</span>
                <span ${"class='icon-chess-"+oppColor+"'"}>${oppHandChessNum}</span>
                `;
            } else {
                oDivOpp.innerHTML = `
                <span>棋盘:</span>
                <span ${"class='icon-chess-"+oppColor+"'"}>${room[oppColor].length}</span>
                `;
            }
        }
        ele.append(oDivOpp);

        // 对手准备
        // if (!room.start) {
            // let tempTwo = document.createElement('span');
            // let tempOne = document.createElement('span');
            // // tempOne.innerHTML = '等待';
            // if (room.ready) {
            //     // tempTwo.innerHTML = '准备';
            //     tempTwo.classList.add('icon-ready');
            // } else {
            //     // tempTwo.innerHTML = '等待';
            //     tempTwo.classList.remove('icon-ready');
            // }
            // tempOne.classList.add('icon-ready');
            // oDivMaster.append(tempOne);
            // oDivOpp.prepend(tempTwo);
        // }
    }

    // 渲染提示信息
    function renderInfoBoxTips(ele, data, second, max = 1) {
        // 限制子元素
        if (ele.children.length >= max) {
            if (ele.children[max - 1]) {
                ele.removeChild(ele.children[max - 1]);
            }
        }
        // 新建子元素
        let oDiv = document.createElement('div');
        oDiv.innerText = data;
        oDiv.classList.add('tips-text');
        // oDiv.classList.add('tips-confirm');
        ele.prepend(oDiv);
        if (second > 0) {
            setTimeout(() => {
                if (oDiv.parentNode == ele) {
                    ele.removeChild(oDiv);
                }
            }, second);
        }
    }


    // 渲染单条消息
    function renderChatlItem(ele, item) {
        // 格式化时间
        let timeFormat = new Date(item.create);
        let h = timeFormat.getHours();
        let m = timeFormat.getMinutes();
        let s = timeFormat.getSeconds();
        if (h <= 9) h = '0' + h.toString();
        if (m <= 9) m = '0' + m.toString();
        if (s <= 9) s = '0' + s.toString();
        timeFormat = h + ":" + m + ":" + s;
        // 世界、房间、系统消息
        let method, methodColor;
        switch (item.method) {
            case "all":
                method = "[世界]";
                methodColor = "purple";
                break;
            case "many":
                method = "[房间]";
                methodColor = "green";
                break;
            case "system":
                method = "";
                break;
            default:
                method = "[世界]";
                methodColor = "purple";
        }

        let chatMsg = html2Escape(item.data);

        let oLi = document.createElement('li');
        oLi.innerHTML = `
        <span style='color:#666;'>${timeFormat}</span>
        <span ${"style='color:"+ methodColor + ";'"}>${method} </span>
        <span>${item.from + '：'} </span>
        <span>${chatMsg}</span>
        `;

        ele.append(oLi);

        // 聊天记录最大100条，这样删除不可找回，所以完全可以存入数据再渲染，如此就能查阅历史记录
        if (ele.children.length > 100) {
            ele.removeChild(ele.children[0]);
        }

        // 一直在底部
        ele.scrollTop = ele.scrollHeight
    }

    // 聊天的内容过滤HTML标签
    function html2Escape(sHtml) {
        return sHtml.replace(/[<>&"]/g, function (c) {
            return {
                '<': '&lt;',
                '>': '&gt;',
                '&': '&amp;',
                '"': '&quot;'
            } [c];
        });
    }

    // 底部功能按钮渲染
    function renderBottomOptsGroup(ele, data) {
        ele.innerHTML = '';
        for (let key in data) {
            let value = data[`${key}`];
            let oSpan = document.createElement('span')
            oSpan.innerText = `${value.content}`;
            ele.append(oSpan);
            // 显示、隐藏
            if (value.hidden) {
                oSpan.setAttribute('hidden', true);
            } else {
                oSpan.removeAttribute('hidden');
            }
            // 前置图标
            if (value.icon) {
                oSpan.classList.add(`${'icon-'+value.icon}`);
            }
            oSpan.classList.add('btn-dark');

            oSpan.addEventListener('click', value.onclick);
        }
    }


})()